/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import util.Utilities;

/**
 *
 * @author Administrator
 */
public class AddBookServletTest extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        if (ServletFileUpload.isMultipartContent(request)) {
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();
            try {
                // Parse the request
                FileItemIterator iter = upload.getItemIterator(request);
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    String fieldName = item.getFieldName();
                    InputStream fin = item.openStream();
                    if (item.isFormField()) {
                        String chineseValue = Utilities.toUTF8(fin);
                        out.println("Form: " + fieldName + " \t\tValue: " + chineseValue + ".</br>");
                    } else {
                        out.println("File: " + fieldName + " \t\tFileNamePath:" + item.getName() + ".</br>");
                        // Process the input stream                    
                        String fileName = item.getName();
                        String contentType = item.getContentType();

                        out.println("Contet type:" + contentType + "</br>");

                        if (!"".equals(fileName)) { // if user ahve select a file
                            fileName = FilenameUtils.getName(fileName);
                            out.println("FileNameOnly" + fileName + "<br>");
                            //String saveDirectory = this.getServletContext().getRealPath("/item");
                            String saveDirectory = "c:/temp";
                            File uploadLocation = new File(saveDirectory, fileName);
                            FileOutputStream fout = new FileOutputStream(uploadLocation);

                            byte[] buf = new byte[256];
                            int read = 0;
                            int total = 0;

                            //todo: check file size
                            while ((read = fin.read(buf)) > 0) {
                                total += read;
                                fout.write(buf, 0, read);
                            }
                            out.println("Size: " + total + "</br>");
                            fin.close();
                            fout.close();
                        }
                    }
                }
            } catch (FileUploadException ex) {
                Logger.getLogger(FileUploadTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
